import multiprocessing
import time
from multiprocessing import Pipe, Process, Queue
def child_process(conn):
   #子进程从连接中接收数据
   conn.send('Hello from child')
   data = conn.recv()
   print('Received:',data)
   conn.close()
if __name__ == '__main__':
   #创建一个管道
   parent_conn, child_conn = Pipe()
   #创建子进程
   p = Process(target=child_process, args=(child_conn,))
   p.start()
 #父进程发送数据到子进程
   parent_conn.send('Hello from parent')
   print('Received:',parent_conn.recv())
   #等待子进程结束
   p.join()


def send_data(pipe):
   #发送数据前先等待一会儿，以便观察recv方法的阻塞行为
   time.sleep(2)
   pipe.send('Hello from parent')
def receive_data(pipe):
   print("Child is waiting to receive data...")
   #尝试从管道接收数据，这个调用是阻塞的
   data = pipe.recv()
   print(f"Child received: {data}")
if __name__ == '__main__':
   #创建一个管道
   parent_pipe, child_pipe = multiprocessing.Pipe()
   #创建子进程
   child_process = multiprocessing.Process(target=receive_data,args=(child_pipe,))
   child_process.start()
   #在父进程中发送数据
   send_data(parent_pipe)
   #等待子进程结束
   child_process.join()

#消息队列
def process1(process_queue):
   print('准备接收数据')
   print('接收到的数据为：',process_queue.get())
if __name__ == '__main__':
   process_queue = Queue(5)
   p1 = Process(target=process1, args=(process_queue, ))
   p1.start()
   time.sleep(2)
   process_queue.put('hello')
   p1.join()
   p1.close()